package com.tadpole.music.view.activity.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.shuyu.waveview.AudioPlayer;
import com.tadpole.music.R;
import com.tadpole.music.bean.me.StudentErrorQuestionBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.me.StudentErrorQuestionIView;
import com.tadpole.music.presenter.me.StudentErrorQuestionPresenter;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.utils.largeImage.InputStreamBitmapDecoderFactory;
import com.tadpole.music.utils.largeImage.LargeImageView;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.base.LookBigPicActivity;
import com.tadpole.music.view.activity.study.ErrorActivity;
import com.tadpole.music.view.activity.study.ErrorExamActivity;
import com.tadpole.music.view.widget.BigImagePopup;
import com.tadpole.music.view.widget.LollipopFixedWebView;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 错题页面
 * Created By 孙岩
 * on 2020/12/26
 */
public class StudentErrorActivity extends BaseActivity implements StudentErrorQuestionIView {
    //回退
    private View view_back_icon;
    //标题
    private TextView actionbar_title;
    //imageView
    private LargeImageView ivImage;
    //title
    private LollipopFixedWebView tvTitle;
    private LinearLayout llA;
    private LinearLayout llB;
    private LinearLayout llC;
    private LinearLayout llD;
    private TextView tvA;
    private TextView tvB;
    private TextView tvC;
    private TextView tvD;
    private ImageView ivA;
    private ImageView ivB;
    private ImageView ivC;
    private ImageView ivD;
    private TextView tvAText;
    private TextView tvBText;
    private TextView tvCText;
    private TextView tvDText;
    private ImageView iv1A;
    private ImageView iv1B;
    private ImageView iv1C;
    private ImageView iv1D;
    //正确答案
    private TextView tvAnswer;
    private RelativeLayout rlAnswer;
    //下一题
    private TextView tvNext;
    //播放text的
    private static AudioPlayer audioText;
    //播放背景的
    private static AudioPlayer audioBg;
    //有音频的选择题 播放12345
    private static MediaPlayer media;
    //标识是2是真题实战还是1是模拟训练
    private int flag;
    //传过来的id
    private int id;
    //获取错题
    private StudentErrorQuestionPresenter studentErrorQuestionPresenter;
    //数据源
    private List<StudentErrorQuestionBean.DataBean> list;
    //index 第一次进来是0
    private int index = 0;
    //播放暂停按钮
    private ImageView ivPlay;
    //是否播放
    private boolean isPlay = false;
    //是否播放完成
    private boolean isPlayFinish = false;
    private String image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_error_question);
        flag = getIntent().getIntExtra("flag", 0);
        id = getIntent().getIntExtra("id", 0);

        initViews();
        initListeners();

        studentErrorQuestionPresenter = new StudentErrorQuestionPresenter();
        studentErrorQuestionPresenter.attachView(this);
        studentErrorQuestionPresenter.getQuestion(id, flag);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        actionbar_title = findViewById(R.id.actionbar_title);
        tvTitle = findViewById(R.id.tvTitle);
        ivImage = findViewById(R.id.ivImage);
        actionbar_title.setText("错题");
        llA = findViewById(R.id.llA);
        llB = findViewById(R.id.llB);
        llC = findViewById(R.id.llC);
        llD = findViewById(R.id.llD);
        tvA = findViewById(R.id.tvA);
        tvB = findViewById(R.id.tvB);
        tvC = findViewById(R.id.tvC);
        tvD = findViewById(R.id.tvD);
        ivA = findViewById(R.id.ivA);
        ivB = findViewById(R.id.ivB);
        ivC = findViewById(R.id.ivC);
        ivD = findViewById(R.id.ivD);
        iv1A = findViewById(R.id.iv1A);
        iv1B = findViewById(R.id.iv1B);
        iv1C = findViewById(R.id.iv1C);
        iv1D = findViewById(R.id.iv1D);
        tvAText = findViewById(R.id.tvAText);
        tvBText = findViewById(R.id.tvBText);
        tvCText = findViewById(R.id.tvCText);
        tvDText = findViewById(R.id.tvDText);
        tvAnswer = findViewById(R.id.tvAnswer);
        rlAnswer = findViewById(R.id.rlAnswer);
        tvNext = findViewById(R.id.tvNext);
        tvTitle.setBackgroundColor(0);

        ivPlay = findViewById(R.id.ivPlay);
    }

    //初始化监听器
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                StudentErrorActivity.this.finish();
            }
        });

        tvNext.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (tvNext.getText().toString().equals("完成")) {
                    StudentErrorActivity.this.finish();
                } else {
                    stopPlay();
                    index = index + 1;
                    showQuestion(list);
                    isPlay = false;
                    isPlayFinish = false;
                    ivPlay.setVisibility(View.GONE);
                }
            }
        });

        ivPlay.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                //如果正在播放 并且没播放完成 暂停
                if(isPlay&&!isPlayFinish){
                    audioBg.pause();
                    isPlay = false;
                    ivPlay.setImageResource(R.mipmap.bofang);
                }else if(!isPlay&&!isPlayFinish){//如果不是正在播放 并且没播放完成 恢复
                    audioBg.play();
                    isPlay = true;
                    ivPlay.setImageResource(R.mipmap.zanting);
                }else if(!isPlay&&isPlayFinish){
                    play(list.get(index).getQuestion().getBg_sound());

                }
            }
        });

        ivImage.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                ArrayList<String> a = new ArrayList<>();
                a.add(image);
                BigImagePopup bigImagePopup = new BigImagePopup(StudentErrorActivity.this,0,a);
                bigImagePopup.showPopupWindow();
            }
        });
    }

    @Override
    public void showList(List<StudentErrorQuestionBean.DataBean> list) {
        this.list = list;
        showQuestion(list);
    }

    //展示
    @SuppressLint({"UseCompatLoadingForDrawables","CheckResult"})
    private void showQuestion(List<StudentErrorQuestionBean.DataBean> list) {
        RequestOptions requestOptions = new RequestOptions()
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        iv1A.setVisibility(View.INVISIBLE);
        iv1B.setVisibility(View.INVISIBLE);
        iv1C.setVisibility(View.INVISIBLE);
        iv1D.setVisibility(View.INVISIBLE);

        if (list.get(index).getQuestion().getTitle_img().equals("")) {
            ivImage.setVisibility(View.GONE);
        } else {
            ivImage.setVisibility(View.VISIBLE);

            image = Constant.IMAGE_HEAD + list.get(index).getQuestion().getTitle_img();
            Glide.with(this).load(Constant.IMAGE_HEAD + list.get(index).getQuestion().getTitle_img()).downloadOnly(new SimpleTarget<File>() {

                @Override
                public void onResourceReady(final File resource, Transition<? super File> transition) {

                    try {
                        //主线程
                        ivImage.setImage(new InputStreamBitmapDecoderFactory(new FileInputStream(resource)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        String url = UrlConfig.getTitle + "q_type=question&id=" + list.get(index).getQuestion().getId();
        tvTitle.loadUrl(url);

        llA.setVisibility(View.VISIBLE);
        llB.setVisibility(View.VISIBLE);
        llC.setVisibility(View.VISIBLE);
        llD.setVisibility(View.VISIBLE);

        if (list.get(index).getQuestion().getAnswer_type() == 1 && list.get(index).getQuestion().getRight_answer() != -1) {//文字

            ivA.setVisibility(View.GONE);
            ivB.setVisibility(View.GONE);
            ivC.setVisibility(View.GONE);
            ivD.setVisibility(View.GONE);
            tvAText.setVisibility(View.VISIBLE);
            tvBText.setVisibility(View.VISIBLE);
            tvCText.setVisibility(View.VISIBLE);
            tvDText.setVisibility(View.VISIBLE);

            tvAText.setText(list.get(index).getQuestion().getAnswer_a());
            tvBText.setText(list.get(index).getQuestion().getAnswer_b());
            tvCText.setText(list.get(index).getQuestion().getAnswer_c());
            tvDText.setText(list.get(index).getQuestion().getAnswer_d());

            if (list.get(index).getQuestion().getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            }
            if (list.get(index).getQuestion().getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            }

        } else if (list.get(index).getQuestion().getAnswer_type() == 2 || list.get(index).getQuestion().getAnswer_type() == 5) {//图片

            ivA.setVisibility(View.VISIBLE);
            ivB.setVisibility(View.VISIBLE);
            ivC.setVisibility(View.VISIBLE);
            ivD.setVisibility(View.VISIBLE);
            tvAText.setVisibility(View.GONE);
            tvBText.setVisibility(View.GONE);
            tvCText.setVisibility(View.GONE);
            tvDText.setVisibility(View.GONE);

            Glide.with(this).load(Constant.IMAGE_HEAD + list.get(index).getQuestion().getAnswer_a()).apply(requestOptions).into(ivA);
            Glide.with(this).load(Constant.IMAGE_HEAD + list.get(index).getQuestion().getAnswer_b()).apply(requestOptions).into(ivB);
            Glide.with(this).load(Constant.IMAGE_HEAD + list.get(index).getQuestion().getAnswer_c()).apply(requestOptions).into(ivC);
            Glide.with(this).load(Constant.IMAGE_HEAD + list.get(index).getQuestion().getAnswer_d()).apply(requestOptions).into(ivD);
            if (list.get(index).getQuestion().getAnswer_c().equals("")) {
                llC.setVisibility(View.GONE);
            }
            if (list.get(index).getQuestion().getAnswer_d().equals("")) {
                llD.setVisibility(View.GONE);
            }
        } else {
            llA.setVisibility(View.GONE);
            llB.setVisibility(View.GONE);
            llC.setVisibility(View.GONE);
            llD.setVisibility(View.GONE);
        }

        String error = list.get(index).getErr_selected();

        switch (error) {
            case "1":
                selectA();
                iv1A.setVisibility(View.VISIBLE);
                break;
            case "2":
                selectB();
                iv1B.setVisibility(View.VISIBLE);
                break;
            case "3":
                selectC();
                iv1C.setVisibility(View.VISIBLE);
                break;
            case "4":
                selectD();
                iv1D.setVisibility(View.VISIBLE);
                break;
            case "0":
                selectNo();
                ToastUtils.show("这道题未作答");
                break;
        }

        if (list.get(index).getQuestion().getRight_answer() == 1) {
            tvAnswer.setText("正确答案是: A");
        } else if (list.get(index).getQuestion().getRight_answer() == 2) {
            tvAnswer.setText("正确答案是: B");
        } else if (list.get(index).getQuestion().getRight_answer() == 3) {
            tvAnswer.setText("正确答案是: C");
        } else if (list.get(index).getQuestion().getRight_answer() == 4) {
            tvAnswer.setText("正确答案是: D");
        }

        if(index+1 == list.size()){
            tvNext.setText("完成");
        }



        playText(list.get(index).getQuestion().getTitle_sound(), list.get(index).getQuestion().getBg_sound(), list.get(index).getQuestion().getPlay_times());
    }

    //播放题干
    @SuppressLint("HandlerLeak")
    private void playText(final String title_sound, final String bg_sound, final int cycler) {
        if (title_sound.equals("")) {
            playBgSound(bg_sound, 0, cycler);
        } else {
            audioText = new AudioPlayer(StudentErrorActivity.this, new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                            break;
                        case AudioPlayer.HANDLER_COMPLETE://text播放结束
                            playCount(bg_sound, 0, cycler);
                            break;
                        case AudioPlayer.HANDLER_PREPARED://播放开始
                            break;
                        case AudioPlayer.HANDLER_ERROR://播放错误

                            break;
                    }

                }
            });
            audioText.playUrl(Constant.IMAGE_HEAD + title_sound);
        }
    }

    //播放背景
    @SuppressLint("HandlerLeak")
    private void playBgSound(final String bg_sound, final int count, final int cycler) {

        audioBg = new AudioPlayer(StudentErrorActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
                        if (cycler == 1) {
                            ivPlay.setImageResource(R.mipmap.bofang);
                            isPlayFinish = true;
                            isPlay = false;
                        } else if (cycler == 2) {
                            if (count != cycler) {
                                playCount(bg_sound, 1, cycler);
                            }else{
                                //两遍播放完成
                                ivPlay.setImageResource(R.mipmap.bofang);
                                isPlayFinish = true;
                                isPlay = false;
                            }

                        } else if (cycler == 3) {
                            if (cycler - count == 2) {//波了一遍了
                                playCount(bg_sound, 1, cycler);

                            } else if (cycler - count == 1) {
                                playCount(bg_sound, 1, cycler);
                            }

                        } else if (cycler == 4) {


                        } else if (cycler == 5) {

                        }
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        ivPlay.setVisibility(View.VISIBLE);
                        isPlay = true;
                        ivPlay.setImageResource(R.mipmap.zanting);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }

            }
        });
        audioBg.playUrl(Constant.IMAGE_HEAD + bg_sound);
    }

    //第一遍 第二遍
    private int rediaCount(int index) {
        int redia = 0;
        switch (index) {
            case 0:
                redia = R.raw.to1;
                break;
            case 1:
                redia = R.raw.to2;
                break;
        }
        return redia;
    }

    //播放第几遍
    @SuppressLint("HandlerLeak")
    private void playCount(final String bg_sound, final int count, final int cycler) {
        if (bg_sound.equals("")) {
            ivPlay.setVisibility(View.GONE);
        } else {
            //播放数量的时候 不是在播放
            isPlay = false;
            if (media != null) {
                media.stop();
                media.release();
            }
            media = MediaPlayer.create(StudentErrorActivity.this, rediaCount(count));
            media.start();
            ivPlay.setVisibility(View.GONE);
            media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    playBgSound(bg_sound, count + 1, cycler);
                }
            });
        }
    }

    //都没选中
    @SuppressLint("UseCompatLoadingForDrawables")
    private void selectNo() {
        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
    }

    //选中a
    @SuppressLint("UseCompatLoadingForDrawables")
    private void selectA() {
        tvA.setBackground(getResources().getDrawable(R.drawable.shape_red_circular_solid));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
    }

    //选中b
    @SuppressLint("UseCompatLoadingForDrawables")
    private void selectB() {
        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_red_circular_solid));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
    }

    //选中c
    @SuppressLint("UseCompatLoadingForDrawables")
    private void selectC() {
        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_red_circular_solid));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
    }

    //选中d
    @SuppressLint("UseCompatLoadingForDrawables")
    private void selectD() {
        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_red_circular_solid));
    }

    //停止播放
    private void stopPlay() {
        //停止播放
        if ( audioBg!= null) {
            audioBg.stop();
            audioBg = null;
        }
        if (audioText != null) {
            audioText.stop();
            audioText = null;
        }
    }

    @SuppressLint("HandlerLeak")
    private void play(String bg_sound){
        audioBg = new AudioPlayer(StudentErrorActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
                        isPlayFinish = true;
                        isPlay = false;
                        ivPlay.setImageResource(R.mipmap.bofang);
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        isPlayFinish = false;
                        isPlay = true;
                        ivPlay.setImageResource(R.mipmap.zanting);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }

            }
        });
        audioBg.playUrl(Constant.IMAGE_HEAD + bg_sound);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlay();
    }
}
